import PropTypes from 'prop-types';
import { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { PlusOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Button, DatePicker, Form, Input, Select, Upload, message } from 'antd';
import Dialog from '@/components/common/Dialog';
import { urlMap, uploadMap } from '@/utils';
import { setTPostInfo } from '@/store/reducers/form';
import { getCityList } from '@/api/city';
import { publishPost } from '@/api/community';
import { setThreadIsRefresh } from '@/store/reducers/active';

const { TextArea } = Input;
const normFile = (e) => e?.fileList || (Array.isArray(e) ? e : []);

function PublishWork(props) {
    const { dialogOpen, onOk, onCancel } = props;
    const [form] = Form.useForm();
    const [selectedValue, setSelectedValue] = useState(null);
    const [cityData, setCityData] = useState([]);
    const { tPostInfo } = useSelector((state) => state.form);
    const dispatch = useDispatch();

    const handleSubmit = async (values) => {
        try {
            const postData = {
                tPostId: tPostInfo.tPostId,
                title: values.title,
                content: values.content,
                place: values.place,
                imagePath: tPostInfo.fileId,
                tags: values.tags,
            };
            publishPost(postData).then((res) => {
                if (res.code === 200) {
                    onOk?.();
                    message.success('发布成功');
                    dispatch(setThreadIsRefresh(true));
                }
            });
        } catch (error) {
            message.error('保存失败');
        }
    };

    // 上传处理
    const handleUploadChange = (info) => {
        if (info.file.status === 'done') {
            const newFileId = info.file.response.data;
            dispatch(setTPostInfo({ ...tPostInfo, fileId: newFileId }));
        }
    };

    const handleRemove = async (file) => {
        try {
            const fileName = file.response?.data;
            await axios.delete(`${urlMap.defaultUrl}${uploadMap.comDeletePath}/${fileName}`, {
                params: { tPostId: tPostInfo.tPostId },
            });
            message.success('删除成功');
            dispatch(setTPostInfo({ ...tPostInfo, fileId: null }));

            const currentList = form.getFieldValue('upload')?.filter((f) => f.uid !== file.uid);
            form.setFieldsValue({ upload: currentList });

            return true;
        } catch (error) {
            message.error('删除失败');
            return false;
        }
    };

    useEffect(() => {
        const fetchCities = async () => {
            try {
                const citiesData = await getCityList();
                const { data: cityList } = citiesData;
                const convertedCities = cityList.map((city) => ({
                    key: city.cityId,
                    value: city.cityName,
                }));

                const sortedCities = [...convertedCities].sort((a, b) => {
                    if (a.value === '广州') return -1;
                    if (b.value === '广州') return 1;
                    return 0;
                });
                setCityData(sortedCities);
            } catch (error) {
                setCityData([]);
            }
        };
        fetchCities();
    }, []);

    return (
        <Dialog
            title="发布作品"
            dialogOpen={dialogOpen}
            onOk={() => form.submit()}
            onCancel={onCancel}
            style={{ height: 540 }}
        >
            <Form
                form={form}
                onFinish={handleSubmit}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 14 }}
                initialValues={{
                    place: cityData[0]?.key || '',
                }}
            >
                <Form.Item label="标题" name="title">
                    <Input />
                </Form.Item>
                <Form.Item label="所在地区" name="place">
                    <Select loading={cityData.length === 0} onChange={setSelectedValue}>
                        {cityData.map((item) => (
                            <Select.Option key={item.key} value={item.key}>
                                {item.value}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="类型" name="tags" rules={[{ required: true, message: '请选择类型' }]}>
                    <Select placeholder="请选择类型">
                        <Select.Option value="1">传统建筑</Select.Option>
                        <Select.Option value="2">特色美食</Select.Option>
                        <Select.Option value="3">地方习俗</Select.Option>
                        <Select.Option value="4">手工艺</Select.Option>
                        <Select.Option value="5">传统服饰</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label="内容" name="content">
                    <TextArea rows={4} />
                </Form.Item>
                {/* <Form.Item label="上传图片"  name="upload"  valuePropName="fileList" getValueFromEvent={normFile}>
          <Upload
            action={urlMap.defaultUrl + uploadMap.comUploadPath}
            listType="picture-card"
            maxCount={1}
            data={() => ({ tPostId: tPostInfo.tPostId })}
            onChange={handleUploadChange}
            onRemove={handleRemove}
          >
           {form.getFieldValue('upload')?.length >= 1 ? null
           : (
              <button style={{ border: 0, background: 'none' }} type="button">
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传</div>
              </button>
            )}
          </Upload>
        </Form.Item> */}
                <Form.Item
                    label="上传图片/视频"
                    name="upload"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    style={{ marginBottom: 32 }}
                >
                    <Upload
                        action={urlMap.defaultUrl + uploadMap.comUploadPath}
                        listType="picture-card"
                        maxCount={1}
                        accept="image/*,video/*"
                        data={() => ({ tPostId: tPostInfo.tPostId })}
                        onChange={handleUploadChange}
                        onRemove={handleRemove}
                        style={{ marginTop: 16 }}
                    >
                        {form.getFieldValue('upload')?.length >= 1 ? null : (
                            <button
                                style={{
                                    border: 0,
                                    background: 'none',
                                    padding: '8px 0',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    alignItems: 'center',
                                }}
                                type="button"
                            >
                                <PlusOutlined />
                                <div style={{ marginTop: 12 }}>上传图片或视频</div>
                            </button>
                        )}
                    </Upload>
                </Form.Item>
            </Form>
        </Dialog>
    );
}
PublishWork.propTypes = {
    dialogOpen: PropTypes.bool,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
};

export default PublishWork;
